<template>
  <div class="show-main">
    <el-scrollbar style="height:100%">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item prop="name">
              <el-input v-model="searchForm.name" clearable placeholder="请输入管理员名称"></el-input>
            </el-form-item>
            <el-form-item prop="status">
              <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
                <el-option label="正常" value="1"></el-option>
                <el-option label="禁用" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click.stop="search(true)">搜索</el-button>
              <el-button type="success" @click.stop="search">刷新</el-button>
              <el-button type="warning" @click.stop="add">添加</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="table" border>
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column prop="phone" label="电话"></el-table-column>
          <el-table-column prop="gender" label="性别">
            <template slot-scope="scope">
              {{scope.row.gender|genderName}}
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <span>
                <el-tooltip :content="scope.row.status == 2 ? '禁用': '正常'" placement="top" :enterable="false">
                  <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2" @change="changeStatus(scope.row)">
                  </el-switch>
                </el-tooltip>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="150">
            <template slot-scope="scope">
              {{scope.row.create_time|formatDate}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button type="text" @click="edit(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="del(scope.row.id)">删除</el-button>
              <el-button type="text" @click="forcePwd(scope.row.id)">强改密码</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchForm.page"
            :page-sizes="[10,20,30,40]" :page-size="searchForm.limit" layout="total, sizes, prev, pager, next, jumper" :total="count">
          </el-pagination>
        </div>
      </el-card>
      <el-dialog title="编辑管理员" :visible.sync="editVisible" :before-close="handleClose('editForm')">
        <el-form ref="editForm" :model="editForm" label-width="80px" :rules="rules">
          <el-form-item label="真实姓名" prop="name">
            <el-input v-model="editForm.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="账号" prop="account">
            <el-input v-model="editForm.account" clearable></el-input>
          </el-form-item>
          <el-form-item label="电话号码" prop="phone">
            <el-input v-model="editForm.phone" maxlength="11" show-word-limit clearable></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="editForm.gender">
              <el-radio :label="1" border>男</el-radio>
              <el-radio :label="2" border>女</el-radio>
              <el-radio :label="0" border>保密</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="绑定角色" prop="role_id">
            <el-select v-model="editForm.role_id" placeholder="请选择角色" clearable>
              <el-option v-for="(item) in roleList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('editVisible', 'editForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('editVisible','editForm')" size="small">编 辑</el-button>
        </span>
      </el-dialog>
      <el-dialog title="添加管理员" :visible.sync="addVisible" :before-close="handleClose('addForm')">
        <el-form ref="addForm" :model="addForm" label-width="80px" :rules="rules">
          <el-form-item label="真实姓名" prop="name">
            <el-input v-model="addForm.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="账号" prop="account">
            <el-input v-model="addForm.account" clearable></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" show-password clearable></el-input>
          </el-form-item>
          <el-form-item label="密码确认" prop="addpassword">
            <el-input v-model="addForm.addpassword" show-password clearable></el-input>
          </el-form-item>
          <el-form-item label="电话号码" prop="phone">
            <el-input v-model="addForm.phone" maxlength="11" show-word-limit clearable></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="addForm.gender">
              <el-radio :label="1" border>男</el-radio>
              <el-radio :label="2" border>女</el-radio>
              <el-radio :label="0" border>保密</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="绑定角色" prop="role_id">
            <el-select v-model="addForm.role_id" placeholder="请选择角色" clearable>
              <el-option v-for="(item) in roleList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('addVisible', 'addForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('addVisible','addForm')" size="small">添 加</el-button>
        </span>
      </el-dialog>
      <el-dialog title="强制修改密码" :visible.sync="forcePwdVisible" :before-close="handleClose('forcePwdForm')">
        <el-form ref="forcePwdForm" :model="forcePwdForm" label-width="80px" :rules="rules">
          <el-form-item label="密码" prop="password">
            <el-input v-model="forcePwdForm.password" show-password clearable></el-input>
          </el-form-item>
          <el-form-item label="密码确认" prop="forpassword">
            <el-input v-model="forcePwdForm.forpassword" show-password clearable></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('forcePwdVisible', 'forcePwdForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('forcePwdVisible','forcePwdForm')" size="small">确 定</el-button>
        </span>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>
<script>
import { getAdminList, getAdminRole, getAdminOnly, addAdmin, changeAdminStatus, editAdmin, forceAdminPwd, delAdmin } from '@/network/api.js'

export default {
  name: 'admins',
  data() {
    return {
      searchForm: {
        page: 1,
        limit: 10,
        name: '',
        status: ''
      },
      table: [],
      count: 0,
      editForm: {
        id: 0,
        name: '',
        account: '',
        phone: '',
        role_id: '',
        gender: ''
      },
      // 添加表单
      addForm: {
        name: '', // 真实姓名
        account: '', // 账号
        password: '', // 密码
        addpassword: '',
        phone: '', // 电话号码
        gender: 1, // 性别 1男 2女 0 保密
        role_id: '' // 角色id
      },
      forcePwdForm: {
        id: 0,
        password: '', // 密码
        forpassword: '' // 密码确认
      },
      roleList: [],
      editVisible: false, // 编辑
      addVisible: false, // 添加
      forcePwdVisible: false, // 强制改密码
      rules: {
        name: [
          { required: true, message: '管理员名称必须', trigger: 'blur' },
          { min: 2, max: 10, message: '名称在 2 到 10 个字符', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '账号必须', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!/^[0-9a-zA-Z]{3,20}$/.test(value)) {
                callback(new Error('账号3到20位数字，大小写字母组成'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码必须', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!/^[0-9a-zA-Z]{6,12}$/.test(value)) {
                callback(new Error('密码6到12位数字，大小写字母组成'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        addpassword: [
          { required: true, message: '密码确认必须', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.addForm.password) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        forpassword: [
          { required: true, message: '密码确认必须', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.forcePwdForm.password) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        phone: [
          { required: true, message: '手机号必须', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!/^1[3456789]\d{9}$/.test(value)) {
                callback(new Error('请输入正确的手机号!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        gender: [{ required: true, message: '性别必须', trigger: 'blur' }],
        role_id: [{ required: true, message: '角色必须', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.search()
  },
  computed: {},
  methods: {
    // 每页条数变化
    handleSizeChange(val) {
      this.searchForm.limit = val
      this.search()
    },
    // 当前页变化
    handleCurrentChange(val) {
      this.searchForm.page = val
      this.search()
    },
    async search(pageInit = false) {
      try {
        if (pageInit === true) {
          this.searchForm.page = 1
        }
        const rtn = await getAdminList(this.searchForm)
        this.table = rtn.list
        this.count = rtn.count
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 添加
    async add() {
      try {
        const rtn = await getAdminRole({})
        this.roleList = rtn
        this.addVisible = true
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 强制修改密码
    forcePwd(id) {
      this.forcePwdForm.id = id
      this.forcePwdVisible = true
    },
    // 修改状态
    changeStatus(row) {
      let msg = ''
      switch (row.status) {
        case 1:
          msg = '您确定要启用该管理员吗?'
          break
        case 2:
          msg = '此操作将禁用该管理员以及旗下所有管理员, 是否确定?'
          break
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            await changeAdminStatus({ id: row.id, status: row.status })
          } catch (e) {
            row.status = row.status === 1 ? 2 : 1
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          row.status = row.status === 1 ? 2 : 1
          this.$message.warning('您已取消操作')
        })
    },
    // 删除
    del(id) {
      this.$confirm('此操作将永久删除该管理员以及旗下所有管理员, 是否确定?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            await delAdmin({ id })
            this.search()
          } catch (e) {
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          this.$message.warning('您已取消操作')
        })
    },
    // 编辑
    async edit(id) {
      try {
        const rtn = await getAdminOnly({ id })
        this.editVisible = true
        this.$nextTick(() => {
          this.editForm = rtn.info
          this.roleList = rtn.roleList
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 关闭弹出前操作(不包括取消按钮)
    handleClose(formName) {
      return done => {
        this.$refs[formName].clearValidate()
        this.$refs[formName].resetFields()
        done()
      }
    },
    // 取消按钮
    close(visibleName, formName) {
      this.$refs[formName].clearValidate()
      this.$refs[formName].resetFields()
      this[visibleName] = false
    },
    send(visibleName, formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          switch (formName) {
            case 'editForm': // 编辑权限
              try {
                await editAdmin(this.editForm)
                this.close(visibleName, formName)
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'addForm': // 添加权限
              try {
                await addAdmin(this.addForm)
                this.close(visibleName, formName)
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'forcePwdForm': // 强制修改密码
              try {
                await forceAdminPwd(this.forcePwdForm)
                this.close(visibleName, formName)
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
          }
        } else {
          this.$message.error('请检查表单')
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
